package com.zhongfl.crm.service.impl.boss;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zhongfl.crm.enums.boss.AmibaCode;
import com.zhongfl.crm.enums.boss.WorkOrderTypeCode;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.mapper.WorkOrderTypeMapper;
import com.zhongfl.crm.model.boss.RedisKeyUtils;
import com.zhongfl.crm.model.boss.WorkOrderType;
import com.zhongfl.crm.service.boss.AmibaService;
import com.zhongfl.crm.service.boss.WorkOrderTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import tech.heptagram.channel.api.common.AssertUtils;
import tech.heptagram.core.common.util.JsonUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 工单类型 服务实现
 *
 * @author tiantian
 * @date 2018/5/3
 */
@Service
@Slf4j
public class WorkOrderTypeServiceImpl implements WorkOrderTypeService {
    @Resource
    private WorkOrderTypeMapper workOrderTypeMapper;
    @Resource
    private AmibaService amibaService;

    @Resource
    private RedisKeyUtils redisKeyUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private String buildFindAllRedisKey() {
        return redisKeyUtils.generateKey("workordertype", "all");
    }

    private void clearAllCache() {
        String findAllRedisKey = buildFindAllRedisKey();
        stringRedisTemplate.opsForValue().getOperations().delete(findAllRedisKey);
    }

    /**
     * 查询所有工单类型
     */
    @Override
    public List<WorkOrderType> findAll() {
        String redisKey = buildFindAllRedisKey();
        String redisValue = stringRedisTemplate.opsForValue().get(redisKey);

        if (StringUtils.isNotEmpty(redisValue)) {
            log.info("从redis中获取 all WorkOrderTypes 工单类型完成, redisKey: {}", redisKey);
            try {
                List<WorkOrderType> workOrderTypes = JsonUtil.fromJson(redisValue, new TypeReference<List<WorkOrderType>>() {});
//                log.info("json parse: {}", workOrderTypes);
                return workOrderTypes;
            } catch (CRMException e) {
                log.error("从redis获取到WorkOrderTypes 解析失败,redisKey:{}", redisKey, e);
            }
        }

        List<WorkOrderType> workOrderTypes = workOrderTypeMapper.selectAll();

        try {
            // 缓存一天
            stringRedisTemplate.opsForValue().set(redisKey, JsonUtil.toJson(workOrderTypes), 1, TimeUnit.DAYS);
        } catch (CRMException e) {
            log.error("向redis添加缓存失败, redisKey:{}", redisKey, e);
        }

        return workOrderTypes;
    }

    @Override
    public WorkOrderType findById(Integer id) {
        AssertUtils.notNull(id, "id为空！");
        return this.findAll().stream()
                .filter(t -> t.getId().equals(id))
                .findFirst().orElse(null);
    }

    @Override
    public WorkOrderType findByCode(WorkOrderTypeCode code) {
        AssertUtils.notNull(code, "code为空！");
        return this.findAll().stream()
                .filter(t -> t.getCode().equals(code))
                .findFirst().orElse(null);
    }

    @Override
    public int save(WorkOrderType workOrderType) {
        AssertUtils.notNull(workOrderType, "参数为空！");
        AssertUtils.notNull(workOrderType.getAmibaSourceId(), "发起方为空！");
        AssertUtils.notNull(workOrderType.getAmibaTargetId(), "目标方为空！");
        AssertUtils.notNull(workOrderType.getName(), "工单类型名称为空！");
        AssertUtils.notNull(workOrderType.getCode(), "工单类型code为空！");

        workOrderType.setName(workOrderType.getCode().getValue());
        String amibaSourceName = amibaService.findById(workOrderType.getAmibaSourceId()).getName();
        workOrderType.setAmibaSourceName(amibaSourceName);
        String amibaTargetName = amibaService.findById(workOrderType.getAmibaTargetId()).getName();
        workOrderType.setAmibaTargetName(amibaTargetName);

        workOrderTypeMapper.insertSelective(workOrderType);

        // 清空缓存
        clearAllCache();

        return workOrderType.getId() ;
    }

    @Override
    public void updateById(WorkOrderType workOrderType) {
        AssertUtils.notNull(workOrderType, "参数为空！");
        AssertUtils.notNull(workOrderType.getId(), "id为空");
        AssertUtils.notNull(workOrderType.getAmibaSourceId(), "发起方为空！");
        AssertUtils.notNull(workOrderType.getAmibaTargetId(), "目标方为空！");
        AssertUtils.notNull(workOrderType.getName(), "工单类型名称为空！");
        AssertUtils.notNull(workOrderType.getCode(), "工单类型code为空！");

        //WorkOrderType type = this.findByCode(workOrderType.getCode());
        //workOrderType.setName(type.getName());
        String amibaSourceName = amibaService.findById(workOrderType.getAmibaSourceId()).getName();
        workOrderType.setAmibaSourceName(amibaSourceName);
        String amibaTargetName = amibaService.findById(workOrderType.getAmibaTargetId()).getName();
        workOrderType.setAmibaTargetName(amibaTargetName);

        workOrderTypeMapper.updateByIdSelective(workOrderType);

        // 清空缓存
        clearAllCache();
    }

    @Override
    public void deleteById(Integer id, String name) {
        AssertUtils.notNull(id, "id为空！");
        AssertUtils.notNull(name, "name为空！");
        workOrderTypeMapper.deleteById(id, name);

        // 清空缓存
        clearAllCache();
    }

    @Override
    public List<WorkOrderType> findByAmibaCodes(List<AmibaCode> amibaCodes) {
        return workOrderTypeMapper.selectByAmibaCodes(amibaCodes);
    }

}
